package com.wenhuitec.android.tang.ui.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.wenhuitec.android.tang.R;
import com.wenhuitec.android.tang.entity.Foods;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

public class FoodsAdapter extends RecyclerView.Adapter<FoodsAdapter.ViewHolder> {

    List<Foods> foodsList;

    private Context mContext;

    private OnClick onClick;


    public FoodsAdapter(Context context, List<Foods> foodsList) {
        this.mContext = context;
        this.foodsList = foodsList;
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView foodNameTv;
        TextView numberTv;
        TextView priceTv;
        LinearLayout linea1;


        public ViewHolder(View view) {
            super(view);
            foodNameTv = (TextView) view.findViewById(R.id.foodNameTv);
            numberTv = (TextView) view.findViewById(R.id.numberTv);
            priceTv = (TextView) view.findViewById(R.id.priceTv);
            linea1 = (LinearLayout) view.findViewById(R.id.linea1);
        }
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_foods, parent, false);
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    public void setFoodsList(List<Foods> foodsList) {
        this.foodsList = foodsList;
        notifyDataSetChanged();
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.foodNameTv.setText(foodsList.get(position).getName());
        holder.numberTv.setText(foodsList.get(position).getNumber());
        holder.priceTv.setText(foodsList.get(position).getPrice());
        holder.linea1.setOnClickListener(view -> {
            if (onClick != null) {
                onClick.onUserClick(foodsList.get(position));
            }
        });
    }

    @Override
    public int getItemCount() {
        return foodsList.size();
    }

    public interface OnClick {
        void onUserClick(Foods foods);
    }

    public void setOnClick(OnClick onClick) {
        this.onClick = onClick;
    }

    public BigDecimal getFoodsStock(String deviceId) {
        BigDecimal stock = new BigDecimal(0);
        List<Foods> foodd = foodsList.stream().filter(foods -> foods.getDeviceId().trim().equals(deviceId.trim())).collect(Collectors.toList());
        for (Foods goo : foodd) {
            stock = stock.add(new BigDecimal(goo.getNumber()));
        }
        return stock;
    }

}
